import Vue from "vue";
import Vuex from "vuex";
import router from "@/router";

Vue.use(Vuex);

function addNewRoute(menuList) {
  let routes = router.options.routes;
  routes.forEach((routeItem) => {
    if (routeItem.path === "/IndexPage") {
      if (!routeItem.children) {
        routeItem.children = [];
      }
      menuList.forEach((menu) => {
        let childRoute = {
          path: "/" + menu.menuClick,
          name: menu.menuName,
          meta: { title: menu.menuName },
          component: () => import("../components/" + menu.menuComponent),
        };
        if (!routeItem.children.some((child) => child.path === childRoute.path)) {
          routeItem.children.push(childRoute);
        }
      });
    }
  });
  router.addRoutes(routes);
}

const store = new Vuex.Store({
  state: {
    menu: [],
  },
  mutations: {
    setMenu(state, menuList) {
      state.menu = menuList;
      localStorage.setItem("menu", JSON.stringify(menuList)); // 存储菜单数据
      addNewRoute(menuList); // 动态添加路由
    },
  },
  getters: {
    getMenu(state) {
      return state.menu;
    },
  },
});

// 恢复菜单数据并动态添加路由
const menuFromStorage = JSON.parse(localStorage.getItem("menu"));
if (menuFromStorage) {
  store.commit("setMenu", menuFromStorage);
}

export default store;
